package com.jianjun.project.system.dept;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.http.Method;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.framework.web.domain.AjaxResult;
import com.jianjun.framework.web.interceptor.DataScope;
import com.jianjun.project.common.model.SysDept;

import java.util.List;


/**
 * 部门信息
 *
 * @author source
 */
@Path(value = "/system/dept")
public class SysDeptController extends Controller {
    @Inject
    SysDeptService deptService;

    @DataScope(deptAlias = "d", permission = "system:dept:list")
    public void list() {
        SysDept dept = JsonKit.parse(getKv().toJson(), SysDept.class);
        List<SysDept> depts = deptService.selectDeptList(dept);
        renderJson(AjaxResult.success(depts));
    }

    @DataScope(deptAlias = "d", permission = "system:dept:query,system:dept:add,system:dept:edit,system:dept:remove")
    public void index() {
        String method = getRequest().getMethod();
        //查询
        if (Method.GET.name().equals(method)) {
            Long deptId = getParaToLong();
            deptService.checkDeptDataScope(deptId);
            renderJson(AjaxResult.success(deptService.selectDeptById(deptId)));
        }
        //新增
        if (Method.POST.name().equals(method)) {
            SysDept dept = JsonKit.parse(getRawData(), SysDept.class);
            if (!deptService.checkDeptNameUnique(dept)) {
                renderJson(AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在"));
                return;
            }
            dept.setCreateBy(SecurityUtils.getUsername());
            renderJson(AjaxResult.success(deptService.insertDept(dept)));
        }
        //修改
        if (Method.PUT.name().equals(method)) {
            SysDept dept = JsonKit.parse(getRawData(), SysDept.class);
            Long deptId = dept.getDeptId();
            deptService.checkDeptDataScope(deptId);
            if (!deptService.checkDeptNameUnique(dept)) {
                renderJson(AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在"));
                return;
            } else if (dept.getParentId().equals(deptId)) {
                renderJson(AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己"));
                return;
            } else if (UserConstants.DEPT_DISABLE.equals(dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
                renderJson(AjaxResult.error("该部门包含未停用的子部门！"));
                return;
            }
            dept.setUpdateBy(SecurityUtils.getUsername());
            renderJson(AjaxResult.success(deptService.updateDept(dept)));
        }
        //删除
        if (Method.DELETE.name().equals(method)) {
            Long deptId = getParaToLong();
            if (deptService.hasChildByDeptId(deptId)) {
                renderJson(AjaxResult.warn("存在下级部门,不允许删除"));
                return;
            }
            if (deptService.checkDeptExistUser(deptId)) {
                renderJson(AjaxResult.warn("部门存在用户,不允许删除"));
                return;
            }
            deptService.checkDeptDataScope(deptId);
            deptService.deleteDeptById(deptId);
            renderJson(AjaxResult.success());
        }
    }

    /**
     * 查询部门列表（排除节点）
     */
    @ActionKey("/system/dept/list/exclude")
    @DataScope(deptAlias = "d", permission = "system:dept:list")
    public void exclude() {
        Long deptId = getParaToLong();
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtil.contains(d.getAncestors().split(Constants.DELIMETER), deptId));
        renderJson(AjaxResult.success(depts));
    }

}
